<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<base href="<%=basePath%>">

<title>Individual Behavior Model</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet"
	href="<%=path%>/xingkong/css/vendor/bootstrap.min.css">
<link href="<%=path%>/xingkong/css/flat-ui.css" rel="stylesheet">
<style type="text/css">
#sigma-container {
	height: 600px;
	margin: auto;
}

.container {
	margin-top: 20px;
}
</style>
</head>

<body>
<div class="container-fluid" style="height:100%">
		<div class="panel panel-primary">
			<div class="panel-body">
				<div class="row">
					<div class="col-lg-2 col-md-2 col-sm-2">
					数据集
					</div>
					<div class="col-lg-3 col-md-3 col-sm-3">
						<select data-toggle="select" id="datasets"
									class="form-control select select-success mrs mbm">
									<option value="none">设置数据集</option>
						</select>
					</div>
					
					
				</div>
				<div class="row">
					<div class="col-lg-2 col-md-2 col-sm-2">
					算法
					</div>
					<div class="col-lg-3 col-md-3 col-sm-3">
						<select data-toggle="select" id="selectalgorithm"
									class="form-control select select-success mrs mbm">
									<option value="LTM">LTM</option>
									<option value="ICM">ICM</option>
						</select>
					</div>
					
					
				</div>
				<p></p>
				<div class="row">
					<div class="col-lg-2 col-md-2 col-sm-2">
					激活节点
					</div>
					<div class="col-lg-4 col-md-4 col-sm-4">
						<select data-toggle="select"
									class="form-control select select-info mrs mbm" id="autoactive">
									<option value="0">随机选择</option>
									<option value="1">手动设置</option>
						</select>
						
					</div>
					<div class="col-lg-4 col-md-4 col-sm-4">
						<input type="text" class="form-control input-sm" id="autoactivenumber"
									placeholder="设置激活节点个数" />
					</div>
				</div>
				<p></p>
				<div class="row">
					<div class="col-lg-2 col-md-2 col-sm-2">
					最佳激活
					</div>
					<div class="col-lg-2 col-md-2 col-sm-2">
						<input type="checkbox"   data-toggle="switch"
									name="info-square-switch" data-on-color="danger"
									id="selectbest" />
					</div>
					<div class="col-lg-2 col-md-2 col-sm-2">
						<input type="text"  class="form-control input-sm"
									placeholder="次数" id="selectbestnumber" />
					</div>
				</div>
				<p></p>
				<div class="row">
					<div class="col-lg-2 col-md-2 col-sm-2">
					迭代阈值
					</div>
					<div class="col-lg-2 col-md-2 col-sm-2">
						<input type="text" class="form-control input-sm" id="maxiterative"
									placeholder="最大迭代次数（默认不限制）" />
					</div>
					<div class="col-lg-2 col-md-2 col-sm-2">
						<button class="btn btn-warning" data-loading-text="计算中..."
									id="cascadeInfo">确   定</button>
					</div>
				</div>
			</div>
		</div>
		<div class="panel panel-primary">
			<div class="panel-body">
				<div id="sigma-container"></div>
			</div>
		</div>
		<div class="panel panel-primary">
			<div class="panel-body">
				<div id="showdetail" style="display:none;">
							<div class="row">
								<div class="col-md-1"></div>
								<div class="col-md-9">运行结果统计</div>
							</div>
							<div class="row">
								<div class="col-md-1"></div>
								<div class="col-md-9">
									<ul class="nav nav-tabs" id="showdetailtab">


									</ul>
									<div id="myTabContent" class="tab-content"></div>

								</div>
							</div>
				</div>
			</div>
		</div>
		<!-- Modal -->
		<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
			aria-labelledby="myModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal"
							aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
						<h4 class="modal-title" id="myModalLabel">运行过程</h4>
					</div>
					<div class="modal-body">
						<textarea class="form-control" style="height:400px;" rows="3"
							id="realtimemessage">计算中...
					</textarea>

					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						<button type="button" class="btn btn-primary" data-dismiss="modal"
							id="copytoclipboard">确定</button>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div id="ajaxdataset" style="display:none;"></div>
	<script src="<%=path%>/xingkong/js/sigma.min.js"></script>
	<script src="<%=path%>/xingkong/js/jquery.min.js"></script>
	<script src="<%=path%>/xingkong/js/jquery-scrolltofixed-min.js"></script>
	<script src="<%=path%>/xingkong/js/highlight.pack.js"></script>
	<script src="<%=path%>/xingkong/js/sigma.plugins.animate.min.js"></script>
	<script src="<%=path%>/xingkong/js/sigma.parsers.json.min.js"></script>
	<script src="<%=path%>/xingkong/js/sigma.plugins.neighborhoods.min.js"></script>
	<script src="<%=path%>/xingkong/js/sigma.plugins.dragNodes.min.js"></script>
	<script src="<%=path%>/xingkong/js/sigma.layout.forceAtlas2.min.js"></script>
	<script src="<%=path%>/xingkong/js/bootstrap.min.js"></script>
	<!--<script src="../js/index.js"></script>-->
	<script src="<%=path%>/xingkong/js/surprise.min.js"></script>
	<script src="<%=path%>/xingkong/js/application.js"></script>
	<script src="<%=path%>/xingkong/js/vendor/video.js"></script>
	<script src="<%=path%>/xingkong/js/flat-ui.min.js"></script>
	<script src="<%=path%>/xingkong/js/comet4j-0.0.2.js"></script>
	<script>
	$.ajax({
		type : "post",//请求方式
		url : "servlet/fileslistservlet",//发送请求地址
		dataType : "json",
		//请求成功后的回调函数有两个参数
		success : function(data) {
			var datats=eval(data);
			datats.forEach(function(mydata) {
				$("#datasets").append("<option value='"+mydata+"'>"+mydata+"</option>"); 
			});
		}
	});
	$("#datasets").change(function(){
		if($(this).val()=="none"){
			$("#ajaxdataset").val("");
		}else{
			initSigma("<%=path%>/duansky/data/"+$(this).val(),2);
			$("#ajaxdataset").val($(this).val());
		}
		
 	 });
    // Add a method to the graph model that returns an
    // object with every neighbors of a node inside:
    sigma.classes.graph.addMethod('neighbors', function(nodeId) {
        var k,
                neighbors = {},
                index = this.allNeighborsIndex[nodeId] || {};

        for (k in index)
            neighbors[k] = this.nodesIndex[k];

        return neighbors;
    });
    var fileName ='<%=path%>/duansky/data/cluster_k_data.json';
	var mysigma;
	initSigma(fileName,1);
	function initSigma(fileName,state){
		if(typeof(mysigma) != "undefined"){
			mysigma.kill();
		}
		sigma.parsers.json(fileName, {
			//container : 'sigma-container'
		}, function(s) {
			mysigma = s;
			mysigma.settings({
				edgeColor : 'default',
				defaultEdgeColor : '#ccc',
			// defaultEdgeType : 'arrow'

			//enableEdgeHovering : true,
			//edgeHoverSizeRatio : 2
			});
			// We first need to save the original colors of our
			// nodes and edges, like this:
			//var initcount=0;
			//console.log("数组长度:"+mysigma.graph.nodes().length);
			mysigma.graph.nodes().forEach(function(n) {
				n.originalColor = n.color;
				n.color="#34495E";
				
				//n.x=(Math.random()*mysigma.graph.nodes().length)|0;
    			//n.y=(Math.random()*mysigma.graph.nodes().length)|0;
    			//initcount++;
			});
			mysigma.graph.edges().forEach(function(e) {
				e.type = "arrow";
				//e.originalColor = e.color;
				e.color = e.originalColor;
				e.size=2;
			});
			if(state=1){
			mysigma.addCamera('cam');
			mysigma.addRenderer({
				  container: document.getElementById('sigma-container'),
				  type: 'canvas',
				  camera: 'cam'
			});
			sigma.renderers.def = sigma.renderers.canvas;
			var dragListener = sigma.plugins.dragNodes(mysigma, mysigma.renderers[0]);
			}
			mysigma.refresh();
			
		});
	}
    
		var cascadeinfojson;
		function showCascadeInfo() {
			
			$.ajax({
				type : "post",//请求方式
				url : "servlet/xingkongservlet",//发送请求地址
				dataType : "json",
				data:{
					ajaxdataset:$("#ajaxdataset").val(),
					algorithm:$("#selectalgorithm").val(),
					autoactive:$("#autoactive").val(),
					autoactivenumber:$("#autoactivenumber").val(),
					selectbest:$("#selectbest").prop("checked")==true?1:0,
					selectbestnumber:$("#selectbestnumber").val(),
					maxiterative:$("#maxiterative").val()
				},
				//请求成功后的回调函数有两个参数
				success : function(data) {
					$("#showdetail").hide();
					$("#showdetailtab").empty();
					$("#myTabContent").empty();
					var activenodesdetail = "";
					var activenodessum = 0;
					cascadeinfojson = eval(data); //解析json对象 
					var count = -1;
					$("#showdetailtab")
							.append(
									"<li role='presentation' class='active'><a href='#nall' id='all'>所有</a></li>");
					$("#myTabContent")
							.append(
									"<div class='tab-pane fade in active' id='nall'></div>");
					cascadeinfojson
							.forEach(function(cascadeNodeList) {
								console.log("第" + (++count) + "次迭代");
								$("#showdetailtab").append(
										"<li role='presentation'><a href='#n"+count+"' id='"+count+"'>"
												+ count + "</a></li>");
								$("#myTabContent")
										.append(
												"<div class='tab-pane fade' id='n"+count+"'></div>");
								cascadeNodeList
										.forEach(function(activeInfo) {
											var adv;
											if (activeInfo.start.length == 0) {
												adv = "初始激活"
														+ activeInfo.active
														+ "节点";
											} else {
												adv = activeInfo.start
														+ "节点激活"
														+ activeInfo.active
														+ "节点";
											}
											//console.log(adv);
											$("#n" + count).html(
													$("#n" + count)
															.html()
															+ adv
															+ "<br>");
											activenodessum++;
											activenodesdetail = activenodesdetail
													+ activeInfo.active
													+ " "
											mysigma.graph
													.nodes(""
															+ activeInfo.active.substring(0,activeInfo.active.indexOf(","))).color = '#E74C3C';
										});
								/*
								$("#showdetailtab a[href='#n"+count+"']").click(function (e) {
									e.preventDefault()
									$(this).tab('show')
									showAnimated(""+$(this).attr("id"));
								});*/
								mysigma.refresh();
							});
					$("#nall").html(
							"有效迭代次数：" + count + "<br>" + "激活了"
									+ activenodessum + "个节点<br>"
									+ activenodesdetail);
					$("#showdetailtab a").click(function(e) {
						e.preventDefault()
						$(this).tab('show')
						showAnimated("" + $(this).attr("id"));
					});
					/*
					$("#showdetailtab a[href='#all']").click(function (e) {
						e.preventDefault()
						$(this).tab('show')
						showAnimated("all");
					});
					 */
					$("#showdetail").show();
				}
			});
		}
		function showAnimated(cascadeNumber) {
			var count = -1;
			mysigma.graph.nodes().forEach(function(n) {
				n.color = n.originalColor;
			});

			mysigma.graph.edges().forEach(function(e) {
				e.color = e.originalColor;
			});

			// Same as in the previous event:
			mysigma.refresh();
			cascadeinfojson
					.forEach(function(cascadeNodeList) {
						console.log("第" + (++count) + "次迭代");
						if (cascadeNumber == "all"|| count < parseInt(cascadeNumber)) {
							cascadeNodeList.forEach(function(activeInfo) {
									mysigma.graph.nodes(""+ activeInfo.active.substring(0,activeInfo.active.indexOf(","))).color = '#E74C3C';
									//blink(""+ activeInfo.active);
							});
							mysigma.refresh();
						}if(count == parseInt(cascadeNumber)){
							cascadeNodeList.forEach(function(activeInfo) {
								activeInfo.start.forEach(function(startnode){
									mysigma.graph.nodes(""+ startnode.substring(0,startnode.indexOf(","))).color = '#2ECC71';
									mysigma.graph.edges().forEach(function(e) {
										if(e.source==mysigma.graph.nodes(""+ startnode.substring(0,startnode.indexOf(","))).id
											&&e.target==mysigma.graph.nodes(""+ activeInfo.active.substring(0,activeInfo.active.indexOf(","))).id){
												e.color = '#2ECC71';
											}
									});
								});
								mysigma.graph.nodes(""+ activeInfo.active.substring(0,activeInfo.active.indexOf(","))).color = '#E74C3C';
									//blink(""+ activeInfo.active);
							});
							mysigma.refresh();
						} else {
							console.log("迭代终止于" + count);
							return false;
						}

					});
		}
		
		
		function invoke(f, start, interval, end) {
			if (!start)
				start = 0;
			if (arguments.length <= 2) {
				setTimeout(f, start);
			} else {
				setTimeout(repeat, start);
				function repeat() {
					var h = setInterval(f, interval);
					if (end)
						setTimeout(function() {
							clearInterval(h)
						}, end);
				}
			}
		}
		function blink(nodeindex){
			var i = 0;
			function getColor() {
				i++;
				switch (i) {
				case 1:
					return "#ffffff";
				case 2:
					return "#ff6600";
				case 3:
					return "#3366cc";
				default:
					return "#f00";
				}
			}
			function colorful(nodeindex) {
				mysigma.graph.nodes(""+ nodeindex).color=getColor();
				mysigma.refresh();
			}
			
			invoke(colorful(nodeindex), 0, 1000, 6000); 
			
		}
		function connect() {
			var realtimemessage = document.getElementById('realtimemessage');
			JS.Engine.on({
				realtimemessage : function(realtimeinfo) {//侦听一个channel  
					realtimemessage.innerHTML = realtimeinfo;
				}
			});
			JS.Engine.start('conn');
		}
		$('#cascadeInfo').on('click', function() {
			
			if($("#ajaxdataset").val()=="") {
			alert("必须选择数据集！");
			}else{
			initSigma("<%=path%>/duansky/data/"+$("#datasets").val(),2);
			var $btn = $(this).button('loading');
			$('#myModal').modal('toggle');
			connect();
			showCascadeInfo();
			$btn.button('reset');
			}
		});
		$('#showdetailtab a').click(function(e) {
			e.preventDefault()
			$(this).tab('show')
		});
		$("#autoactive").change(function(){
		if($(this).val()==0){
			$("#autoactivenumber").attr("placeholder", "设置激活节点个数");
			$("#selectbest").bootstrapSwitch('disabled', false);
			//$("#selectbest").prop("checked",true);
			$("#selectbestnumber").removeAttr("disabled");
		}
		if($(this).val()==1){
			$("#autoactivenumber").attr("placeholder", "设置节点列表,以逗号分隔(0-"+mysigma.graph.nodes().length+")");
			$("#selectbest").bootstrapSwitch('disabled', true);
			//$("#selectbest").prop("checked",false);
			$("#selectbestnumber").attr("disabled","disabled");
		}
 	 });
 	 
 	 //selectbest
</script>
</body>
</html>
